package com.sesame.controller;

import com.sesame.api.FMSConfig;
import com.sesame.entity.FileReqEntity;
import kim.sesame.framework.exception.BusinessException;
import kim.sesame.framework.utils.*;
import kim.sesame.framework.web.controller.AbstractWebController;
import kim.sesame.framework.web.response.Response;
import kim.sesame.framework.web.util.FileUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * @author johnny
 * @date 2017-06-10 13:10
 * @Description:
 */
@CommonsLog
@RestController
public class UploadController extends AbstractWebController {

    @Autowired
    private FMSConfig fmsConfig;

    @RequestMapping("/upload")
    public Response upload(FileReqEntity fileReqEntity) throws Exception {
        boolean flgFileEmpty = fileReqEntity.getFile() == null || fileReqEntity.getFile().getSize() == 0;
        if (flgFileEmpty && StringUtil.isEmpty(fileReqEntity.getFileBase64())) {
            throw new BusinessException("fileBase64 和 file 不能同时为空");
        }
        Argument.notEmpty(fileReqEntity.getModule(), "模块 (module) 不能为空");

        String src = null;// 文件的路径,返回结果

        // 生成路径
        if (StringUtil.isEmpty(fileReqEntity.getPath())) {
            String path = getFullFile(fileReqEntity.getModule());
            fileReqEntity.setPath(path);
        }
        // 检查文件类型,是文件流的形式就检查
        if (!(flgFileEmpty) && StringUtil.isEmpty(fileReqEntity.getFileType())) {
            fileReqEntity.setFileType(fileReqEntity.getFile().getOriginalFilename().substring(fileReqEntity.getFile().getOriginalFilename().lastIndexOf(".")));
        }
        // 生成文件名称
        String fileName = getFileName(fileReqEntity.getFileType());

        // 检查路径是否存在
        String filePath = fmsConfig.getFilePath() + "/" + fileReqEntity.getPath();
        checkAndCreate(filePath);

        filePath = filePath + "/" + fileName;

        // 判断那种形式上传的
        if (flgFileEmpty) {
            // base64 字符串
            byte[] b = ImgBase64.imageConversionByte(fileReqEntity.getFileBase64());
            OutputStream out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            out.close();
        } else {
            // 文件流
            saveFile(filePath, fileReqEntity.getFile());
        }
        src = fmsConfig.getMapping() + "/" + fileReqEntity.getPath() + "/" + fileName;
        return returnSuccess(src);
    }

    /**
     * 删除文件
     *
     * @param path 文件路径
     * @return
     */
    @RequestMapping("/delete")
    public Response delete(String path) {
        if (StringUtil.isNotEmpty(path)) {
            // 判断是否包含http头
            if (path.contains(fmsConfig.getMapping())) {
                path = path.replace(fmsConfig.getMapping(), "");
            }
            // 判断路径是否存在
            File file = new File(fmsConfig.getFilePath() + path);
            if (file.exists()) {
                // 存在就删除
                FileUtil.clearFiles(file);
            } else {
                throw new BusinessException("文件路径不存在");
            }
        }
        return returnSuccess();
    }


    public void saveFile(String targetFilePath, MultipartFile file) throws Exception {
        File targetFile = new File(targetFilePath);
        OutputStream outputstream = null;
        InputStream inputstream = null;
        try {
            outputstream = new FileOutputStream(targetFile);
            inputstream = file.getInputStream();
            FileCopyUtils.copy(inputstream, outputstream);
        } finally {
            if (outputstream != null) {
                outputstream.flush();
                outputstream.close();
            }
            if (inputstream != null) {
                inputstream.close();
            }
        }


    }

    /**
     * 获取文件全路径
     *
     * @param module
     * @return
     */
    private String getFullFile(String module) {
        String datefile = DateUtils.convert(new Date(), "yyyy/MM/dd");
        return module + "/" + datefile;
    }

    /**
     * 生成文件名
     *
     * @param fileType
     * @return
     */
    private String getFileName(String fileType) {
        return UUIDUtil.getShortUUID() + fileType;
    }

    public void checkAndCreate(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}